﻿using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using SX.AuthServer.Data;
using SX.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace SX.AuthServer.Models
{
    public class CustomProfileService : IProfileService
    {
        private readonly ApplicationDbContext _dbContext;
        public CustomProfileService(ApplicationDbContext appContext)
        {
           
            _dbContext = appContext;

        }
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject?.GetSubjectId();
            if (sub == null) throw new Exception("用户Id为空");

            var user = _dbContext.Set<ApplicationUser>().Where(x => x.Id== sub).FirstOrDefault();
            if (user == null)
            {
                Console.WriteLine("用户{0}不存在", sub);
                //_logger?.LogWarning("用户{0}不存在", sub);
            }
            else
            {
                var claims = new List<Claim>()
                {
                    new Claim(ClaimNames.UserId, user.Id),
                    new Claim(ClaimNames.UserName, user.UserName)
                };
                context.IssuedClaims = claims;
            }
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            //这里存在疑问
            var sub = context.Subject?.GetSubjectId();
            if (sub == null) throw new Exception("用户Id为空");
            var user = _dbContext.Set<ApplicationUser>().Where(x => x.Id == sub).FirstOrDefault();
            context.IsActive = true;
        }
    }
}
